package com.iot.manage.service;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 全局token管理服务
 *
 * @author zhanglei
 */
@Service
public class TokenService {

	/**
	 * 全局token容器
	 */
	@Autowired
	@Qualifier("tokenMap")
	private Map<String, String> tokenMap;

	/**
	 * 校验token是否存在
	 *
	 * @param token
	 * @return
	 */
	public synchronized boolean validate(String token) {
		if (StringUtils.isNotEmpty(token)) {
			if (tokenMap.containsKey(token)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 设置用户的token
	 *
	 * @param loginName
	 * @return
	 */
	public synchronized String setToken(String loginName) {
		// 生成token
		String token = generatedToken(loginName);
		tokenMap.put(token, loginName + RandomUtils.nextInt(000000, 999999));
		return token;
	}

	/**
	 * 移除用户的token
	 *
	 * @param token
	 */
	public synchronized void removeToken(String token) {
		tokenMap.remove(token);
	}

	/**
	 * 刷新全局token容器的生命周期（默认30分钟）
	 */
	@Scheduled(initialDelay = 1800000L, fixedRate = 1800000L)
	public synchronized void clearTokenMap() {
		if (MapUtils.isNotEmpty(tokenMap)) {
			tokenMap.clear();
		}
	}

	/**
	 * 生成token
	 * <p>
	 * （ loginName + 当前服务器时间 ）散列哈希
	 * </p>
	 *
	 * @param loginName
	 * @return
	 */
	private synchronized String generatedToken(String loginName) {
		StringBuilder sb = new StringBuilder(loginName);
		sb.append(LocalDateTime.now().toString());
		sb.append(RandomUtils.nextInt(000000, 999999));
		return DigestUtils.sha1Hex(sb.toString());
	}

}
